<template>
  <div>
    <el-table :data="messages">
      <el-table-column prop="id" label="ID"></el-table-column>
      <el-table-column prop="content" label="内容"></el-table-column>
      <el-table-column prop="user.username" label="用户"></el-table-column>
      <el-table-column prop="createdAt" label="发布时间" :formatter="formatDate"></el-table-column>
      <el-table-column prop="read" label="已读" :formatter="formatRead"></el-table-column>
    </el-table>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import axios from '../plugins/axios'

interface User {
  id: number;
  username: string;
  password: string;
  email: string;
  fullName: string | null;
  gender: string | null;
  phone: string | null;
  birthDate: string | null;
  undergraduateSchool: string | null;
  targetUniversity: string | null;
  personalBio: string | null;
  role: string;
}

interface Message {
  id: number;
  content: string;
  user: User;
  parent: Message | null;
  createdAt: string;
  read: boolean;
}

const messages = ref<Message[]>([])

const fetchMessages = async () => {
  try {
    const response = await axios.get('http://localhost:8080/api/messages/all')
    messages.value = response.data
  } catch (error) {
    console.error('Failed to fetch messages:', error)
  }
}

// 日期格式化函数
const formatDate = (row: any, column: any, cellValue: string) => {
  const date = new Date(cellValue)
  const options: Intl.DateTimeFormatOptions = {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    hour: '2-digit',
    minute: '2-digit'
  }
  return date.toLocaleDateString('zh-CN', options)
}

// 已读状态格式化函数
const formatRead = (row: any, column: any, cellValue: boolean) => {
  return cellValue ? '是' : '否'
}

onMounted(() => {
  fetchMessages()
})
</script>

<style scoped>
.el-table {
  width: 100%;
}
</style>